const dotenv = require('dotenv')
const OpenAI = require('openai')

dotenv.config()

const openai = new OpenAI({
    // apiKey: process.env.OPENAI_API_KEY,
    // baseURL: "https://api.chatanywhere.tech/v1"
    apiKey: process.env.DOUBAO_API_KEY,
    baseURL: process.env.DOUBAO_BASE_URL,
});

const getOpenAIResponse = async (input) => {
    const chatCompletion = await openai.chat.completions.create({
        messages: input,
        model: process.env.DOUBAO_MODEL,
    });
    return chatCompletion.choices[0].message.content
}

/**
 * 自定义错误类
 */
class DoubaoAIError extends Error {
    constructor(message, status, code) {
      super(message);
      this.name = 'DoubaoAIError';
      this.status = status;
      this.code = code;
    }
  }
/**
 * HTTP流式聊天完成请求
 * @param {string} content - 用户输入内容
 * @param {Function} onChunk - 数据块回调函数 (chunk: string) => void
 * @param {Function} onComplete - 完成回调函数 () => void
 * @param {Function} onError - 错误回调函数 (error: Error) => void
 * @param {string} model - 模型名称
 * @param {Object} options - 额外选项
 */
async function createStreamingChatCompletion(messages, onChunk, onComplete, onError, model = process.env.DOUBAO_MODEL, options = {}) {
    try {
      const streamResponse = await openai.chat.completions.create({
        messages,
        model,
        stream: true,
        ...options
      });
  
      for await (const part of streamResponse) {
        const chunk = part.choices[0]?.delta?.content || '';
        if (chunk && onChunk) {
          onChunk(chunk);
        }
      }
      
      if (onComplete) {
        onComplete();
      }
      
    } catch (error) {
      const doubaoError = new DoubaoAIError(`流式请求失败: ${error.message}`, error.status, error.code);
      if (onError) {
        onError(doubaoError);
      } else {
        throw doubaoError;
      }
    }
  }
module.exports = {
    getOpenAIResponse,
    createStreamingChatCompletion
}
